package im.demo.fileserv;

import im.demo.fileserv.db.tables.Files;
import im.demo.fileserv.db.tables.records.FilesRecord;
import org.jooq.*;
import org.jooq.impl.DSL;
import org.jooq.impl.DefaultConfiguration;
import org.jooq.types.UInteger;

import java.io.IOException;
import java.sql.*;
import java.util.List;
import java.util.Properties;

public class DB {

    private static Connection conn;

    private static Configuration config;

    static {

        try {

            Properties props = new Properties();

            props.load(DB.class.getClassLoader().getResourceAsStream("jdbc.properties"));

            // load config

            Class.forName(props.getProperty("jdbc.driver"));

            conn = DriverManager.getConnection(
                    props.getProperty("jdbc.url"),
                    props.getProperty("jdbc.username"),
                    props.getProperty("jdbc.password")
            );

            config = new DefaultConfiguration()
                    .set(conn)
                    .set(SQLDialect.MYSQL);

        } catch (IOException | SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static Integer addFile(String _fileKey, String _originName) {
        DSLContext ctx = DSL.using(config);
        return ctx.insertInto(Files.FILES,
                Files.FILES.ORIGIN_NAME,
                Files.FILES.FILE_KEY
        ).values(_originName, _fileKey).execute();
    }

    public static List<FilesRecord> getAllFile(Integer _offset, Integer _limit) {
        DSLContext ctx = DSL.using(config);
        return ctx.selectFrom(Files.FILES).limit(_limit).offset(_offset).fetch();
    }

    public static FilesRecord getFileByFileKey(String fileKey) {
        DSLContext ctx = DSL.using(config);
        return ctx.selectFrom(Files.FILES).where(Files.FILES.FILE_KEY.equal(fileKey)).fetchOne();
    }

    public static FilesRecord getFileById(Integer id) {
        DSLContext ctx = DSL.using(config);
        return ctx.selectFrom(Files.FILES).where(Files.FILES.ID.equal(UInteger.valueOf(id))).fetchOne();
    }

}
